﻿using Guids;
using MiniJob.Entity;

namespace MiniJob.Service;

public interface IDataSeedService
{
    /// <summary>
    /// 初始化种子数据：添加默认应用
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    Task SeedAsync(CancellationToken cancellationToken);
}

public class DataSeedService(
    IFreeSql freeSql, 
    IGuidGenerator guidGenerator, 
    IAppService appService,
    ILogger<DataSeedService> logger) 
    : IDataSeedService
{
    public async Task SeedAsync(CancellationToken cancellationToken)
    {
        var defaultApp = freeSql.Select<AppInfo>()
            .Where(p => p.Name == MiniJobConsts.DefaultApp)
            .First();
        if (defaultApp == null)
        {
            var newSalt = Guid.NewGuid().ToString("N");
            var password = Encrypt.Md5((MiniJobConsts.DefaultPassword + newSalt));
            defaultApp = new AppInfo
            {
                Id = guidGenerator.Create(),
                Name = MiniJobConsts.DefaultApp,
                Description = "默认应用",
                Password = password,
                Salt = newSalt
            };
            await appService.InsertAsync(defaultApp);
            logger.LogInformation("Init default app {AppName} successful.", MiniJobConsts.DefaultApp);
        }
    }
}
